<!--
 * @author dumeng
 -->
<template>
  <div v-loading="pageLoading" class="content-classify-page">
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in typeList" :key="item.dict" :label="item.name" :name="item.dict" />
      </el-tabs>
    </div>
    <div v-if="activeTab === 'RWFL'" class="classify-tab">
      <el-tabs v-model="characterTab" @tab-click="characterTabClick">
        <el-tab-pane v-for="item in dict.RWFL" :key="item.dictValue" :label="item.dictName" :name="item.dictValue" />
      </el-tabs>
    </div>
    <template v-if="activeTab !== 'FLLX_BQ'">
      <div class="classify-btn">
        <div class="btn-title">
          <span>分类管理</span>
        </div>
        <div class="btn-btns">
          <el-button v-if="!allListIsEdit" @click="handleAddClassify">添加分类</el-button>
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        size="mini"
        :indent="30"
        :cell-style="rowStyle"
        :header-cell-style="headerStyle"
      >
        <el-table-column label="分类名称">
          <template slot-scope="scope">
            <template v-if="scope.row.isEdit">
              <el-input
                v-model="scope.row.classifyName"
                class="edit-input"
                :class="[scope.row.parentId != -1 && 'children']"
                size="small"
                :maxlength="15"
              />
              <el-button v-if="!allListIsEdit" class="addchild-btn" size="small" type="text" @click="addchild(scope.row)">添加子分类</el-button>
            </template>
            <template v-else>
              <span :class="[scope.row.parentId != -1 && 'children']">{{ scope.row.classifyName }}</span>
              <el-button v-if="!allListIsEdit" class="addchild-btn" size="small" type="text" @click="addchild(scope.row)">添加子分类</el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          v-if="activeTab === 'RWFL' || activeTab === 'JNZQFL06' || activeTab === 'JNZQFL05'"
          label="分类图片"
          width="180"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.isEdit">
              <el-image :src="view + scope.row.imgId" @click.native="fileFlag = 1">
                <div slot="error" style="cursor: pointer;" class="image-slot">
                  点击上传
                </div>
              </el-image>
              <image-no-cropper-upload
                v-if="fileFlag === 1"
                ref="imageUpload"
                accept="image/*"
                :limit="1"
                :multiple="false"
                @close="fileFlag = -1"
                @success="
                  (id) => {
                    ;(scope.row.imgId = id), (fileFlag = -1)
                  }
                "
              >
                <div slot="tip" class="upload-tip">
                  <i class="el-icon-info" />
                  请上传图片
                </div>
              </image-no-cropper-upload>
            </template>
            <template v-else>
              <el-image :src="view + scope.row.imgId" :preview-src-list="[view + scope.row.imgId]">
                <template v-slot:error>
                  <img
                    src="../images/error-icon.png"
                    alt
                    style="width: 100px;height: 100px; background: rgb(193, 187, 187);"
                  />
                </template>
              </el-image>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="ZT01" inactive-value="ZT02" @change="changeStatus(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column v-if="activeTab === 'RWFL'" label="职工端是否展示" width="150">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isAppVisit" active-value="1" inactive-value="0" @change="changeShow(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="移动" width="150">
          <template slot-scope="scope">
            <el-button :disabled="scope.row.isFirst" type="text" @click="move(scope.row, 'SY')">上移</el-button>
            <el-button :disabled="scope.row.isLast" type="text" @click="move(scope.row, 'XY')">下移</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <template v-if="scope.row.isEdit">
              <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleSave(scope.row)">保存</el-button>
              <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleCancel(scope.row)">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleUpdate(scope.row)">编辑</el-button>
            </template>
            <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-else>
      <label-category />
    </template>
  </div>
</template>
<script>
import labelCategory from '@/views/contentRepository/labelLibrary/pages/category.vue'
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload'
import {
  getDictByCode,
  fetchList,
  del,
  insert,
  update,
  updateStatus,
  move,
  otherFetchList,
  otherInsert,
  otherUpdate,
  otherUpdateStatus,
  otherDel,
  otherMove,
  characterList,
  characterdel,
  characterinsert,
  characterupdate,
  characterStatus,
  charactermove
} from './../api/index'
import permission from '@/directive/permission/index.js' // 权限判断指令
export default {
  name: 'RevealCategory',
  components: { labelCategory, ImageNoCropperUpload },
  directives: { permission },
  filters: {
    formatStatus(val) {
      return val === 0 ? '启用' : val === 1 ? '禁用' : '禁用'
    },
    formatIshot(val) {
      return val === 0 ? '是' : val === 1 ? '否' : '否'
    }
  },
  data() {
    return {
      fileFlag: -1,
      view: '/API-DOCUMENT/document/file/download?id=',
      pageLoading: true,
      activeTab: 'JNZQFL03',
      characterTab: '',
      listLoading: false,
      searchshow: true,
      expandAll: true,
      list: [],
      curEditRow: {},
      allListIsEdit: false, // 分类树是否存在编辑情况，如果存在隐藏所有的添加下级按钮
      sortable: null,
      typeList: [
        // {
        //   dict: 'JNZQFL01',
        //   name: '课程分类'
        // },
        // {
        //   dict: 'JNZQFL04',
        //   name: '闯关分类'
        // },
        {
          dict: 'JNZQFL03',
          name: '题库分类'
        },
        {
          dict: 'JNZQFL05',
          name: '视频分类'
        },
        {
          dict: 'JNZQFL06',
          name: '音频分类'
        },
        {
          dict: 'JNZQFL07',
          name: '文档分类'
        },
        {
          dict: 'FLLX_TP',
          name: '图片分类'
        },
        {
          dict: 'RWFL',
          name: '人物分类'
        },
        {
          dict: 'FLLX_BQ',
          name: '标签分类'
        }
      ],
      dict: {
        RWFL: []
      },
      treeLevel: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    rowStyle({ row, columnIndex }) {
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    headerStyle({ row, columnIndex }) {
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    /**
     * 切换是否在职工端展示
     */
    changeShow(row) {
      console.log(row, 'row')
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const params = {
          id: row.id,
          classifyName: row.classifyName,
          status: row.status,
          parentId: row.parentId,
          classifyType: row.classifyType,
          imgId: row.imgId,
          isAppVisit: row.isAppVisit
        }
        return new Promise((resolve, reject) => {
          characterupdate(params)
            .then(() => {
              this.$message({
                message: '处理成功',
                type: 'success',
                duration: 2000
              })
              loading.close()
              this.getList()
            })
            .catch((error) => {
              loading.close()
              this.getList()
              reject(error)
            })
        })
      }
    },
    /**
     * 分类移动
     */
    async move(row, dir) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        if (this.activeTab === 'FLLX_TP') {
          await otherMove({ id: row.id, msg: dir })
        } else if (this.activeTab === 'RWFL') {
          await charactermove({ id: row.id, msg: dir })
        } else {
          await move({ id: row.id, msg: dir })
        }
        this.$message({
          message: '处理成功',
          type: 'success',
          duration: 2000
        })
        loading.close()
        this.getList()
      } catch {
        loading.close()
        this.getList()
      }
    },
    /**
     * 切换启用禁用状态
     */
    async changeStatus(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        try {
          if (this.activeTab === 'FLLX_TP') {
            await otherUpdateStatus({ id: row.id, status: row.status })
          } else if (this.activeTab === 'RWFL') {
            await characterStatus({ id: row.id, status: row.status })
          } else {
            await updateStatus({ id: row.id, status: row.status })
          }
          this.$message({
            message: '处理成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.getList()
        } catch {
          loading.close()
        }
      }
    },
    /**
     * 获取字典
     */
    getDict(code) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((response) => {
            loading.close()
            this.dict[code] = response.data.data && response.data.data.length > 0 ? response.data.data[0].list : []
            this.characterTab = this.dict.RWFL[0].dictValue
            this.getList()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    levelRange(s) {
      const reg = /^\+?[1-9][0-9]*$/
      if (reg.test(s)) {
        this.treeLevel = Number(s)
      } else {
        this.treeLevel = ''
      }
    },
    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      // this.levelRange(this.dict['XWFL'][tab.index].dictRemark)
      if (this.activeTab === 'RWFL') {
        for (const key in this.dict) {
          this.getDict(key)
        }
      } else if (this.activeTab !== 'FLLX_BQ') {
        this.getList()
      }
    },
    // 人物选项卡
    characterTabClick(tab, event) {
      this.getList()
    },
    handleCancel(row) {
      if (row.id) {
        row['classifyName'] = this.curEditRow.classifyName
        row['status'] = this.curEditRow.status
        row['imgId'] = this.curEditRow.imgId
        this.findPathByLeafId(row.id, this.list).isEdit = false
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
      }
      this.allListIsEdit = false
    },
    handleUpdate(row) {
      if (this.allListIsEdit) {
        this.$message({
          message: '请先保存新添加分类',
          type: 'warning'
        })
        return
      } else {
        this.allListIsEdit = true
        this.curEditRow = Object.assign({}, row)
        this.findPathByLeafId(row.id, this.list).isEdit = true
      }
    },
    handleSave(row) {
      var obj = {
        id: row.id,
        classifyName: row.classifyName,
        status: row.status,
        parentId: row.parentId
      }
      if (this.activeTab === 'RWFL') {
        this.$set(obj, 'classifyType', this.characterTab)
        this.$set(obj, 'imgId', row.imgId)
      } else {
        if (this.activeTab === 'JNZQFL06' || this.activeTab === 'JNZQFL05') {
          this.$set(obj, 'imgId', row.imgId)
        }
        this.$set(obj, 'classifyType', this.activeTab)
      }
      this.save(obj)
    },
    async save(obj) {
      if (!obj.classifyName) {
        this.$message({
          message: '请填写分类名称',
          type: 'warning'
        })
        return
      }
      const pattern = new RegExp("^\\s|[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]|\\s$")
      if (pattern.test(obj.classifyName)) {
        this.$message({
          message: '请勿输入特殊字符或前后空格',
          type: 'warning'
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (obj.id) {
        try {
          if (this.activeTab === 'FLLX_TP') {
            await otherUpdate(obj)
          } else if (this.activeTab === 'RWFL') {
            await characterupdate(obj)
          } else {
            await update(obj)
          }
          this.allListIsEdit = false
          this.$message({
            message: '处理成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.getList()
        } catch {
          loading.close()
        }
      } else {
        try {
          if (this.activeTab === 'FLLX_TP') {
            await otherInsert(obj)
          } else if (this.activeTab === 'RWFL') {
            await characterinsert(obj)
          } else {
            await insert(obj)
          }
          this.allListIsEdit = false
          this.$message({
            message: '处理成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.getList()
        } catch {
          loading.close()
        }
      }
    },
    handleDel(row) {
      if (row.id) {
        this.$confirm('此操作将永久删除该课程分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.del(row.id)
          })
          .catch(() => {})
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
        this.allListIsEdit = false
      }
    },
    async del(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        if (this.activeTab === 'FLLX_TP') {
          await otherDel({ id: id })
        } else if (this.activeTab === 'RWFL') {
          await characterdel({ id: id })
        } else {
          await del({ id: id })
        }
        loading.close()
        this.$message({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      } catch {
        loading.close()
      }
    },
    getList() {
      this.allListIsEdit = false
      this.listLoading = true
      if (this.activeTab === 'FLLX_TP') {
        return new Promise((resolve, reject) => {
          otherFetchList({ classifyType: this.activeTab })
            .then((response) => {
              this.listLoading = false
              this.list = this.initData(response.data.data)
              this.pageLoading = false
            })
            .catch((error) => {
              this.listLoading = false
              this.pageLoading = false
              reject(error)
            })
        })
      } else if (this.activeTab === 'RWFL') {
        return new Promise((resolve, reject) => {
          characterList({ classifyType: this.characterTab })
            .then((response) => {
              this.listLoading = false
              this.list = this.initData(response.data.data)
              this.pageLoading = false
            })
            .catch((error) => {
              this.listLoading = false
              this.pageLoading = false
              reject(error)
            })
        })
      } else {
        const params = {
          classifyType: this.activeTab
        }
        return new Promise((resolve, reject) => {
          fetchList(params)
            .then((response) => {
              this.listLoading = false
              this.list = this.initData(response.data.data)
              this.pageLoading = false
            })
            .catch((error) => {
              this.listLoading = false
              this.pageLoading = false
              reject(error)
            })
        })
      }
    },
    /**
     * 递归增加是否可以上移下移标识
     * @param data
     * @returns {*}
     */
    initData(data, level = 1) {
      data.forEach((item, index) => {
        item['isFirst'] = false
        item['isLast'] = false
        item['isEdit'] = false
        if (index === 0) {
          item['isFirst'] = true
        }
        if (index === data.length - 1) {
          item['isLast'] = true
        }
        item['level'] = level
        if (item.children && item.children.length > 0) {
          return this.initData(item.children, level + 1)
        }
      })
      return data
    },
    addchild(row) {
      this.allListIsEdit = true
      row['_expanded'] = true
      /* let length = ''
      if (row.children) {
        length = row.children.length
      } else {

      }*/
      const obj = {
        id: '',
        classifyName: '',
        status: 'ZT01',
        isFirst: true,
        isLast: true,
        isEdit: true,
        parentId: row.id
      }
      this.findPathByLeafId(row.id, this.list).children.unshift(obj)
    },
    /**
     * 根据id递归查找所在的对象
     * @param data
     * @returns {*}
     */
    findPathByLeafId(leafId, nodes, path) {
      if (path === undefined) {
        path = {}
      }
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = path
        if (leafId === nodes[i].id) {
          tmpPath = nodes[i]
          return tmpPath
        }
        if (nodes[i].children) {
          var findResult = this.findPathByLeafId(leafId, nodes[i].children, tmpPath)
          console.log('3333', findResult)
          if (findResult) {
            return findResult
          }
        }
      }
    },
    handleAddClassify() {
      this.allListIsEdit = true
      const list = this.list
      var length = list.length
      const obj = {
        id: '',
        parentId: '',
        classifyName: '',
        status: 'ZT01',
        isEdit: true,
        isFirst: true,
        isLast: true,
        index: length
      }
      list.unshift(obj)
      this.$set(this, 'list', list)
    },
    handleFilter() {
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
$dark_gray: #bfced6;
.content-classify-page {
  padding: 20px;
  .classify-tab {
    width: 100%;
    margin-bottom: 10px;
    background-color: #fff;
    padding: 0 10px;
    .el-tabs__header {
      margin: 0;
    }
  }
  .classify-btn {
    display: flex;
    height: 46px;
    line-height: 46px;
    .btn-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
  .el-table {
    background-color: transparent;
    /* .cell {
      display: flex;
      align-items: center;
    } */
    thead {
      th {
        font-size: 14px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(166, 166, 166, 1);
      }
    }
    th,
    tr {
      background-color: transparent;
    }
    tbody {
      background-color: #ffffff;
      font-weight: 500;
    }
  }
}
</style>
<style scoped lang="scss">
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
  vertical-align: middle;
}

.edit-input {
  padding-right: 80px;
  &.children {
    padding-left: 20px;
  }
}

.addchild-btn {
  position: absolute;
  right: 15px;
  // top: 6px;
  padding: 0;
}
</style>
